// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: GPL-3.0-only

package trace_cmd

import (
	"fmt"
	"strings"
	"time"

	"gitcode.com/opendragonfly/df_proto_gen_go.git/trace_api"
	"gitcode.com/opendragonfly/df_server/config"
	"gitcode.com/opendragonfly/df_server/utils"
	"github.com/spf13/cobra"
)

var getTraceCmd = &cobra.Command{
	Use: "getTrace",
	PreRunE: func(cmd *cobra.Command, args []string) error {
		if len(args) != 3 {
			return fmt.Errorf("need param [serviceName] [serviceVersion] [traceId]")
		}
		return nil
	},
	RunE: func(cmd *cobra.Command, args []string) error {
		cfg, err := config.ReadServerConfig()
		if err != nil {
			return err
		}
		if cfg.SuperToken == "" {
			return fmt.Errorf("miss super token in config")
		}
		conn, err := utils.ConnGrpcServer(fmt.Sprintf("127.0.0.1:%d", cfg.Port.ServicePort))
		if err != nil {
			return err
		}
		defer conn.Close()

		serviceName := args[0]
		serviceVersion := args[1]
		traceId := args[2]

		client := trace_api.NewTraceApiClient(conn)
		res, err := client.GetTrace(cmd.Context(), &trace_api.GetTraceRequest{
			AccessToken: cfg.SuperToken,
			Service: &trace_api.ServiceInfo{
				ServiceName:    serviceName,
				ServiceVersion: serviceVersion,
			},
			TraceId: traceId,
		})
		if err != nil {
			return err
		}
		if res.Code != trace_api.GetTraceResponse_CODE_OK {
			return fmt.Errorf("%s", res.ErrMsg)
		}
		fmt.Println("traceId", res.Trace.TraceId)
		fmt.Printf("%s startTime:%s,endTime:%s,consumeTime:%dms\n", res.Trace.RootSpan.SpanName,
			time.UnixMilli(res.Trace.RootSpan.StartTimeStamp).Format(time.DateTime),
			time.UnixMilli(res.Trace.RootSpan.EndTimeStamp).Format(time.DateTime),
			res.Trace.RootSpan.EndTimeStamp-res.Trace.RootSpan.StartTimeStamp,
		)
		attrList := []string{}
		for _, attr := range res.Trace.RootSpan.AttrList {
			attrList = append(attrList, fmt.Sprintf("%s=%s", attr.Key, attr.Value))
		}
		if len(attrList) > 0 {
			fmt.Printf("    attrs:%s\n", strings.Join(attrList, ","))
		}
		return nil
	},
}
